#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re

from pyquery import PyQuery

from base.gsxt_base_worker import GsxtBaseWorker
from common.global_field import Model

'''
1. 搜索没有结果判断功能添加
'''


class GsxtGanSuWorker(GsxtBaseWorker):
    def __init__(self, **kwargs):
        GsxtBaseWorker.__init__(self, **kwargs)

    def get_search_result_html(self, keyword, session):
        # keyword = '甘肃金隆宜路桥建设（集团）有限公司'
        # keyword = '甘肃中石油昆仑燃气有限公司'
        param_list = []
        try:
            # keyword = 'fdsfasljfjsadlf'
            url = 'http://{host}/gsxygs/'.format(host=self.host)
            content = self.get_captcha_geetest(url, '#text_query', '#input_img', keyword, 'div#u5_img.queryTip',
                                               proxy_type=2)
            if content is None:
                return param_list, self.SEARCH_ERROR

            if PyQuery(content, parser='html').find('div#u5_img.queryTip').find('span').eq(1).text() == '0':
                return param_list, self.SEARCH_NOTHING_FIND

            pattern = 'detail\(this,\'(.*?)\',\'(.*?)\'\);'
            regex = re.compile(pattern)
            search_list = regex.findall(content)
            if len(search_list) > 0:
                for item in search_list:
                    param_list.append({
                        'pripid': item[0],
                        'entcate': item[1],
                    })
        except Exception as e:
            self.log.exception(e)
            return param_list, self.SEARCH_ERROR

        return param_list, self.SEARCH_SUCCESS if len(param_list) > 0 else self.SEARCH_ERROR

    @staticmethod
    def __get_company_name(text):
        jq = PyQuery(text, parser='html')
        search_list = jq.find('#entNameFont').text()
        if len(search_list) > 0:
            return search_list.strip()

        return None

    # 基本信息
    def get_base_info(self, session, pri_pid, ent_cate):
        url = 'http://{host}/gsxygs/pubSearch/basicView'.format(host=self.host)

        post_data = {
            'pripid': pri_pid,
            'entcate': ent_cate,
            'queryType': 'query',
            'entname': '',
            'geetest_challenge': '',
            'geetest_validate': '',
            'geetest_seccode': '',
        }

        # 基本信息
        r = self.task_request(session.post, url, data=post_data)
        if r is None:
            return None, None, None

        return url, r.text, post_data

    # 获得年报信息
    def get_annual_info(self, session, data, text):
        if text == '' or text is None:
            return
        try:
            pattern = 'ancheClick\(\'(.*?)\',\'(.*?)\',\'(.*?)\'\);'
            regex = re.compile(pattern)
            search_list = regex.findall(text)

            if len(search_list) > 0:
                for item in search_list:
                    url = 'http://{host}/gsxygs/anche/ancheInfo'.format(host=self.host)
                    post_data = {
                        'ancheId': item[0],
                        'entcate': item[1],
                        'ancheyear': item[2],
                    }
                    r = self.task_request(session.post, url, data=post_data)
                    if r is None:
                        continue

                    self.append_model(data, Model.annual_info, url, r.text,
                                      year=item[2], classify=Model.type_detail,
                                      post_data=post_data)
        except Exception as e:
            self.log.exception(e)

    def get_key_person_info(self, session, data, pri_pid, ent_cate):
        url = 'http://{host}/gsxygs/pubSearch/personView'.format(host=self.host)
        post_data = {
            'pripid': pri_pid,
            'entcate': ent_cate,
        }
        r = self.task_request(session.post, url, data=post_data)
        if r is None:
            return
        self.append_model(data, Model.key_person_info, url, r.text, post_data=post_data)

    # 获得分支结构信息
    def get_branch_info(self, session, data, pri_pid, ent_cate):
        # fzjgForm
        url = 'http://{host}/gsxygs/pubSearch/fzjgView'.format(host=self.host)
        post_data = {
            'pripid': pri_pid,
            'entcate': ent_cate,
        }
        r = self.task_request(session.post, url, data=post_data)
        if r is None:
            return

        self.append_model(data, Model.branch_info, url, r.text, post_data=post_data)

    def get_detail_html_list(self, seed, session, param_list):
        # 保存企业名称
        data_list = []
        rank = 0
        for item in param_list:
            try:
                pri_pid = item.get('pripid', None)
                ent_cate = item.get('entcate', None)
                url, base_text, post_data = self.get_base_info(session, pri_pid, ent_cate)
                if url is None:
                    continue

                # 获得公司名称
                company_name = self.__get_company_name(base_text)
                if company_name is None or company_name == '':
                    self.log.error('公司名称解析失败..pripid = {pripid} encate = {encate}'.format(
                        pripid=pri_pid, encate=ent_cate, text=base_text))
                    continue

                # 建立数据模型
                rank += 1
                data = self.get_model(company_name, rank, seed, self.province)

                # 存储数据
                self.append_model(data, Model.base_info, url, base_text, post_data=post_data)

                # 获得主要人员信息
                self.get_key_person_info(session, data, pri_pid, ent_cate)

                # 获得分支结构信息
                self.get_branch_info(session, data, pri_pid, ent_cate)

                # 年报信息
                self.get_annual_info(session, data, base_text)

                data_list.append(data)
            except Exception as e:
                self.log.exception(e)

        self.target_db.insert_batch_data(self.target_table, data_list)
        return len(data_list)
